<?php

/**
 * Description of DALLeague
 *
 * @author aethv
 */
class DALLeague extends DALBase{
    
    public function __construct() {
        parent::__construct();
        $this->_tbl = 'league';
        $this->_key = 'id';
    }
    
    public function updateLeagueConfig($obj){
        $leagueRunning = array();
        $leagueStop = array();
        for ($i = 0; $i < count($obj); $i++) {
            $row = $obj[$i];
            if($row['status'] == 0){
                $leagueStop[] = $row['id'];
            }else{
                $leagueRunning[] = $row['id'];
            }
        }
        if(count($leagueRunning) > 0){
            $listId = implode(',', $leagueRunning);
            $sql = "UPDATE league SET STATUS = 1 WHERE id IN ($listId)";
            $this->executeQuery($sql);
        }
        if(count($leagueStop) > 0){
            $listId = implode(',', $leagueStop);
            $sql = "UPDATE league SET STATUS = 0 WHERE id IN ($listId)";
            $this->executeQuery($sql);
        }
    }
    
    public function save($data){
        $query = "";
        
        $id = $data->id;
        $tblID = $this->getByID($id);
        if ($tblID) {
            $query = "UPDATE $this->_tbl SET ";
                $query .= " `name`='$data->name'";
                $query .= ", `countryId`='$data->countryId'";
                $query .= ", `modify_timestamp`=now()";
            $query .= " WHERE `id`=$id";
        }else{
            $query = "INSERT INTO $this->_tbl  (`id`, `name`, `countryId`, `status`) VALUES (";
                $query .= $id;
                $query .= " ,'$data->name'";
                $query .= " ,'$data->countryId'";
                $query .= " ,0";
            $query .= ");";
        }
//        echo $query;
        $result = $this->executeQuery($query);
        if($result){
            if($tblID){
                return $tblID;
            }
            return mysql_insert_id();
        }
        return -1;
    }
    
    public function getLeaguesClosing(){
        $query = "select * from $this->_tbl "
                . "where modify_timestamp > DATE_SUB(now(), INTERVAL 2 HOUR) "
                . "ORDER BY modify_timestamp desc";
        $data = array();
        $result = $this->executeQuery($query);
        if ($result) {
            //  Scan through the resource
            while ($row = mysql_fetch_object($result)) {
                //  put row object into the array
                $data[] = $row;
            }
        }
        //
        return $data;
    }
}